<?php
defined("BASEPATH") OR exit("No direct script access allowed");

class XunJian extends CI_Controller
{
    private $appId;
    private $appSecret;
    private $compName;
    private $tableName;


    /**
     * XunJian constructor.
     */
    public function __construct()
    {
        parent::__construct();
        $this->appId = "wwc6bba99e4709d99c";
        $this->appSecret = "22JHgq9o-SshfwrrOK76p5DcakUZmIJwgBC7STdXo4w";
        $this->compName = "容百科技";
        $this->tableName = "weixininfo_rb";
    }

    public function index(){
        $userid = "6522";
        $jsapiTicket = $this->getJsApiTicket();
        // 注意 URL 一定要动态获取，不能 hardcode.
        $protocol = (!empty($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] !== "off" || $_SERVER["SERVER_PORT"] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        //var_dump($jsapiTicket);
        $signature = sha1($string);

        $signPackage = array(
            "appId"     => $this->appId,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string,
            "userid"    => $userid,
            "createTime"=> time()
        );
        $this->load->view("XunJian",$signPackage);
    }

    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    private function getJsApiTicket() {
        // jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
        //$data = json_decode(file_get_contents("weixinJS/jsapi_ticket.json"));
        $data = $this->Data_model->get_single_data(array("type" => "jsapi_ticket","compname" => $this->compName),$this->tableName);
        if ($data["time"] < time() || $data === null) {
            $accessToken = $this->get_access_token();
            // 如果是企业号用以下 URL 获取 ticket
            $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
            //$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            $res = json_decode($this->http_request_json($url));
            $ticket = $res->ticket;
            if ($ticket) {
                if($data === null){
                    $this->Data_model->add_data(array("compname" => $this->compName,"type" => "jsapi_ticket","jsapi_ticket" => $ticket),$this->tableName);
                }else{
                    $this->Data_model->update_data(array("type" => "jsapi_ticket"),array("time" => time() + 7000,"jsapi_ticket" => $ticket),$this->tableName);
                }

                /*
                        $data->expire_time = time() + 7000;
                $data->jsapi_ticket = $ticket;
                $fp = fopen("weixinJS/jsapi_ticket.json", "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
                 *
                 */
            }
        } else {
            $ticket = $data["jsapi_ticket"];
        }
        return $ticket;
    }

    function get_access_token(){
        $result = $this->Data_model->get_single_data(array("compname"=>$this->compName,"type"=>"access_token"),$this->tableName);
        if($result["time"] < time() || $result === null){
            $corpid = $result["corpid"];
            $corpsecret = $result["corpsecret"];
            if($result === null){
                $corpid = $this->appId;
                $corpsecret = $this->appSecret;
            }
            $url="https://qyapi.weixin.qq.com/cgi-bin/gettoken?&corpid=".$corpid."&corpsecret=".$corpsecret;
            
            $json=self::http_request_json($url);//这个地方不能用file_get_contents
            $data=json_decode($json,true);
            if(isset($data["access_token"])){
                if($result === null){
                    $this->Data_model->add_data(array("compname"=>$this->compName,"corpid" => $this->appId,"corpsecret" => $this->appSecret,"type"=>"access_token","access_token" => $data["access_token"]),$this->tableName);
                }else{
                    $this->Data_model->update_data(array("compname"=>$this->compName,"type"=>"access_token"),array("access_token" => $data["access_token"],"time" => time()+7100),$this->tableName);
                }
                $access_token = $data["access_token"];
            }else{
                return "获取access_token错误";
            }
        }else{
            $access_token = $result["access_token"];
        }
        return $access_token;
    }

    function http_request_json($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

}